import React,{ useState } from 'react'
import { Field, Flex, Popup, Picker, Button, Toast } from 'react-vant'
import { ArrowDown,Exchange } from '@react-vant/icons'
import { useNavigate } from 'react-router-dom'
import { _sendCode,_verifyCode,_checkPhone,_loginByPhoneCode } from '../../api/login'
import login_css from './index.module.scss'
import { connect } from 'react-redux'
import {changeLogin} from '../../store/actions/login'
const columns = ['86 🇨🇳', '1 🇺🇸', '88 🏳️‍🌈', '89 🏳️‍⚧️', '90 🇴🇲', '91 🇵🇪', '92 🇩🇪']

function Login(props) {
  const [sms, setSms] = useState('')
  const [code, setCode] = useState('')
  const [visible, setVisible] = useState(false)
  const [field, setVield] = useState(columns[0])
  const navigate = useNavigate()
  const countryCode = field.split(' ')[0]
  const [codeTime,setCodeTime] = useState(0)

  //检测手机号码是否已注册
  function checkPhone() {
    _checkPhone(sms,countryCode).then(res=>{
      // res.exist===-1?navigate('/register'):Toast.success('登录成功') && navigate('/home')
      res.exist===-1?Toast.success('暂时未开放注册') && navigate('/home'):Toast.success('登录成功') && navigate('/home')
    }).catch(err => { Toast.info(err.msg || err.message) })
  }
  //发送验证码
  async function getPhoneCode() {
    if(sms==='') return Toast.info('请输入手机号码')
    const res = await _sendCode(sms,countryCode).catch(err => Toast.info(err.msg || err.message))
       if(res.code === 200){
          Toast.success('验证码发送成功') 
          setCodeTime(10)
          var time =10
          var timer = setInterval(() => {
            console.log('----',time);
            time--
            if(time<=0){
              setCodeTime(0)
              clearInterval(timer)
            }
            setCodeTime(time)
          }, 1000);
      }
  }
  //登录
  async function login() {
    if(sms==='') return Toast.info('请输入手机号码')
    if(code==='') return Toast.info('请输入验证码')
    const verifyCode = await _verifyCode(sms,code,countryCode).catch(err => { Toast.info(err.msg || err.message) })
    if( verifyCode.code!==200 )  return Toast.info('验证码错误')
    const loginByPhoneCode = await _loginByPhoneCode(sms,code).catch(err => { 
      console.log(err);
      // if (err.code === 410) return navigate('/register')
      if (err.code === 410) return Toast.success('暂时未开放注册') && navigate('/home')
      Toast.info(err.msg || err.message) 
    })
    if( loginByPhoneCode.code!==200 )  return Toast.info('登录失败')
    localStorage.setItem('cookie',loginByPhoneCode.cookie)
    localStorage.setItem('isLogin',JSON.stringify({isLogin:true,uid:loginByPhoneCode.profile.userId}))
    props.changeLogin({isLogin:true,uid:loginByPhoneCode.profile.userId})
    checkPhone()
  } 


  return (
    <div className={login_css.page}>
      <Flex align='center'>
        <Flex.Item span={14}><h2>手机验证码登录</h2></Flex.Item>
        <Exchange color='#3f45ff' fontSize='20px'/>
      </Flex>
      <span className={login_css.tip}>未注册手机号请去网易云App创建账号</span>
      <div className={login_css.field}>
        <Field
          value={sms}
          center
          label='手机号'
          placeholder='请输入手机号'
          onChange={setSms}
          prefix={
            <Flex align='center' onClick={() => setVisible(true)}>
              +{field} <ArrowDown style={{ paddingLeft: 8 }} />
            </Flex>
          }
        />
        <Field
          value={code}
          center
          label='验证码'
          placeholder='输入验证码'
          onChange={setCode}
          suffix={
            <Button size='small' loading={codeTime===0?false:true} type={codeTime===0?'primary':'success'} loadingText={codeTime} onClick={getPhoneCode}>
              发送验证码
            </Button>
          }
        />
      </div>

      <Button 
        type='primary' 
        block round 
        className={login_css.login_btn}
        onClick={login}>
        点击登录
      </Button>

      <Popup
        round
        visible={visible}
        position='bottom'
        onClose={() => setVisible(false)}
      >
        <Picker
          title='选择国家/地区'
          onConfirm={(value) => {
            setVield(value)
            setVisible(false)
          }}
          columns={columns}
        />
      </Popup>
    </div>
  )
}
export default connect(
  state =>({
    
}),{
    changeLogin
})(Login)
